package org.nanotek.http;

import java.io.File;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpFileUpload {
	
	private URI myUploadUrl;

	public void testUpload() throws Exception {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(myUploadUrl);

		MultipartEntity reqEntity = new MultipartEntity(
			HttpMultipartMode.BROWSER_COMPATIBLE);

		reqEntity.addPart("string_field",
			new StringBody("field value"));

		FileBody bin = new FileBody(new File("/foo/bar/test.png"));
		reqEntity.addPart("attachment_field", bin );

		httppost.setEntity(reqEntity);

		System.out.println("executing request " + httppost.getRequestLine());
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity resEntity = response.getEntity();

		if (resEntity != null) {
			String page = EntityUtils.toString(resEntity);
			System.out.println("PAGE :" + page);
		}
	}
}
